package fr.hoteia.appengine.archetype.server.web.servlet.cron;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;
import com.google.appengine.api.taskqueue.TaskOptions.Method;

/**
 * <p>
 * <a href="HotHandlerCronServlet.java.html"><i>View Source</i></a>
 * </p>
 *
 * @author Denis GOSSET <a href="http://www.hoteia.com"><i>Hoteia.com</i></a>
 * 
 */
public class HotHandlerCronServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private Queue queue;

	public void init(ServletConfig sc) throws ServletException {
		synchronized (HotHandlerCronServlet.class) {
			super.init(sc);
			queue = QueueFactory.getQueue("HotHandlerQueue");
		}
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

	public void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		String path = request.getPathInfo();
		
		if (path.startsWith("/start")) {
			addHotHandlerTasks();
		}
	}

	private void addHotHandlerTasks() {
		try {
		  for (int i = 0; i < 15; i++) {
			  for (int j = 0; j < 6; j++) {
				  addHotHandlerTask();
			  }
		  }
		} catch(Exception e){
			e.printStackTrace();
		}
	}
	
	private void addHotHandlerTask() {
		try {
		  TaskOptions taskOpts = TaskOptions.Builder.withUrl("/queue/hotHandler/start");
		  taskOpts.method(Method.GET);
		  taskOpts.param("startHotHandler", "true");
		  queue.add(taskOpts);
		  
		} catch(Exception e){
			e.printStackTrace();
		}
	}

}
